{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二叉堆"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "二叉堆是一种特殊的堆，二叉堆是完全二元树（二叉树）或者是近似完全二元树（二叉树）。二叉堆有两种：最大堆和最小堆。最大堆：父结点的键值总是大于或等于任何一个子节点的键值；最小堆：父结点的键值总是小于或等于任何一个子节点的键值。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "队列的一个重要变种称为优先级队列。优先级队列的作用就像一个队列,你可以通过从前面删除一个项目来出队。然而,在优先级队列中,<span class=\"girk\">队列中的项的逻辑顺序由它们的优先级</span>确定。最高优先级项在队列的前面,最低优先级的项在后面。因此,当你将项排入优先级队列时,新项可能会一直移动到前面。为了更好地实现堆，我们采用完全二叉树保持平衡。\n",
    "\n",
    "<img src=\"image/chapter05/heap.png\" width=450>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 二叉堆的操作如下：<br> $\\bullet$ BinaryHeap():创建一个空的二叉堆对象;<br>$\\bullet$ insert(k): 将新元素加入到堆中;<br>$\\bullet$ findMin(): 返回堆中的最小项，最小项仍保留在堆中;<br> $\\bullet$ delMin(): 返回堆中的最小项，同时从堆中删除;<br>$\\bullet$ isEmpty(): 返回堆是否为空;<br> $\\bullet$  size(): 返回堆中节点的个数;<br>$\\bullet$ buildHeap(list)：从一个包含节点的列表里创建新堆"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于整个二叉堆可以由单个列表表示,所以构造函数将初始化列表和一个currentSize属性来跟踪堆的当前大小.你会注意到,一个空的二叉堆有一个单一的零作为heapList的第一个元素,这个零只是放那里,用于以后简单的整数除法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### class BinHeap:\n",
    "    def __init__(self):\n",
    "        self.heaList = [0]\n",
    "        self.currentSize = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来要实现的是insert方法。首先，为了满足“完全二叉树”的性质，新键值应该添加到列表的末尾。然而新键值简单地添加在列表末尾，显然无法满足堆次序。但我们可以通过比较父节点和新加入的元素的方法来重新满足堆次序。如果新加入的元素比父节点要小，可以与父节点互换位置.\n",
    "\n",
    "<img src=\"image/chapter05/Heap.png\" width=400>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们现在可以编写insert方法了,插入方法中的大部分工作都是由子结点向子树根结点交换完成的，这个过程一直是向上的。一直持续遇到根结点。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "delMin的难点在根被删除后恢复堆结构和堆顺序属性。\t我们可以分两步恢复我们的堆。首先,我们将通过获取列表中的最后一个项并将其移动到根位置来恢复根项,保持我们的堆结构属性。\t但是,我们可能已经破坏了我们的二叉堆的堆顺序属性。第二,我们通过将新的根节点沿着树向下推到其正确位置来恢复堆顺序属性。\n",
    "\n",
    "<img src=\"image/chapter05/delmin.png\" width=400>\n",
    "\n",
    "为了维护堆顺序属性,我们所需要做的是将根节点和最小的子节点交换。在初始交换之后,我们可以将节点和其子节点重复交换,直到节点被交换到正确的位置,使它小于两个子节点。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了完成我们对二叉堆的讨论,我们将看从一个列表构建整个堆的方法。你可能想到的第一种方法如下所示。给定一个列表,通过一次插入一个键轻松地构建一个堆。由于你从一个项的列表开始,该列表是有序的,可以使用二分查找找到正确的位置,以大约O(log^n)操作的成本插入下一个键。但是,请记住,在列表中间插入项可能需要O(n)操作来移动列表的其余部分,为新项腾出空间。因此,要在堆中插入n个键,将需要总共\tO(nlogn)操作。\t然而,如果我们从整个列表开始,那么我们可以在O(n)操作中构建整个堆。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下图展示[9,6,5,2,3]的初始树中的节点移动到其正确位置时所做的交换。虽然我们从树的中间开始,并以我们的方式回到根节点, 并确保最大的子节点总是沿着树向下移动。因为堆是一个完整的二叉树,超过中途点的任何节点都将是树叶,因此没有子节点。注意,当i=1时,我们从树的根节点向下交换,因此可能需要多次交换。正如你在图中最右边的两个树中可以看到的,首先9从根位置移出,但是9在树中向下移动一级之后, percDown检查下一组子树,以确保它被推到下一层。在这种情况下,它与3进行第二次交换。现在9已经移动到树的最低层,不能进行进一步交换。\n",
    "\n",
    "<img src=\"image/chapter05/initialheap.png\" width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 完整代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 3 5 6 9 "
     ]
    }
   ],
   "source": [
    "# 子结点下标为ｉ的父节点为ｉ//2\n",
    "# 父节点下标为ｉ的子结点下标为2*ｉ和2*ｉ+1\n",
    "\n",
    "class BinHeap:\n",
    "    def __init__(self):\n",
    "        self.heapList = [0] # 为的是二叉堆结点在表中的下标从１开始\n",
    "        self.currentSize = 0\n",
    "    #------------------------- 构建二叉堆--------------------------------#\n",
    "    def percDown(self,i):\n",
    "        while (i * 2) <= self.currentSize:\n",
    "            mc = self.minChild(i)\n",
    "            if self.heapList[i] > self.heapList[mc]:\n",
    "                tmp = self.heapList[i]\n",
    "                self.heapList[i] = self.heapList[mc]\n",
    "                self.heapList[mc] = tmp\n",
    "            i = mc\n",
    "\n",
    "    def minChild(self,i):\n",
    "      # 子树结点度为１的情况\n",
    "        if i * 2 + 1 > self.currentSize:\n",
    "            return i * 2\n",
    "      # 子树结点度为2的情况\n",
    "        if self.heapList[i*2] < self.heapList[i*2+1]:\n",
    "            return i * 2\n",
    "        else:\n",
    "            return i * 2 + 1\n",
    "        \n",
    "    def buildHeap(self,alist):\n",
    "        i = len(alist) // 2\n",
    "        self.currentSize = len(alist)\n",
    "        self.heapList = [0] + alist[:]\n",
    "        while (i > 0):\n",
    "            self.percDown(i)\n",
    "            i = i - 1\n",
    "    \n",
    "    #-----------------------------插入新数据，重建二叉堆--------------------#\n",
    "    def percUp(self,i):\n",
    "        while i not in (0,1): \n",
    "            if self.heapList[i] < self.heapList[i // 2]:\n",
    "                tmp = self.heapList[i // 2]\n",
    "                self.heapList[i // 2] = self.heapList[i]\n",
    "                self.heapList[i] = tmp\n",
    "            i = i // 2\n",
    "\n",
    "    def insert(self,k):\n",
    "        self.heapList.append(k)\n",
    "        self.currentSize = self.currentSize + 1\n",
    "        self.percUp(self.currentSize)\n",
    "    \n",
    "    #----------------------------- 返回并删除最小值------------------------#\n",
    "\n",
    "    def delMin(self):\n",
    "        retval = self.heapList[1]\n",
    "        self.heapList[1] = self.heapList[self.currentSize]\n",
    "        self.currentSize = self.currentSize - 1\n",
    "        self.heapList.pop()\n",
    "        self.percDown(1)\n",
    "        return retval\n",
    "\n",
    "\n",
    "\n",
    "bh = BinHeap()\n",
    "bh.buildHeap([9,5,6,2,3])\n",
    "\n",
    "for i in range(5):\n",
    "    print(bh.delMin(),end=' ')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 来看看Ｐｙｔｈｏｎ内置的二叉堆模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[9, 23, 48, 51, 64, 85, 48, 98, 86, 81]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from heapq import heappush,heappop\n",
    "from random import randrange\n",
    "Q = []\n",
    "for i in range(10):\n",
    "    heappush(Q,randrange(100))\n",
    "Q"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[9, 23, 48, 48, 51, 64, 81, 85, 86, 98]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[heappop(Q) for i in range(10)]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
